//
//  ChangeLinkVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/9/15.
//

import UIKit
import WebKit

class ChangeLinkVC: ZMViewController {
    
    // MARK: - UI
    // 状态
    @IBOutlet weak var stateImg: UIImageView!
    @IBOutlet weak var state: UILabel!
    // 清空
    @IBOutlet weak var clearView: UIStackView!
    // 内容
    @IBOutlet weak var textView: UITextView!
    // 粘贴提示
    @IBOutlet weak var tip: UIView!
    // 成功提示
    @IBOutlet weak var succTipView: UIStackView!
    @IBOutlet weak var succTip: UILabel!
    // 转换
    @IBOutlet weak var nextBtn: UIButton!
    // 重新转换 复制
    @IBOutlet weak var resultBtnView: UIStackView!
    @IBOutlet weak var resetBtn: UIButton!
    @IBOutlet weak var copyBtn: UIButton!
    // 转链教程
    @IBOutlet weak var webBgView: UIView!
    @IBOutlet weak var webView: UIView!
    @IBOutlet weak var webViewHeight: NSLayoutConstraint!
    // 成功商品
    @IBOutlet weak var resultView: UIView!
    @IBOutlet weak var resultList: UITableView!
    @IBOutlet weak var resultHeight: NSLayoutConstraint!
    
    lazy var wkWeb: WKWebView = {
        let userContentController = WKUserContentController()
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = userContentController
        wkWebConfig.allowsInlineMediaPlayback = true
        let web = WKWebView(frame: CGRect.zero, configuration: wkWebConfig)
        web.scrollView.showsVerticalScrollIndicator = false
        web.backgroundColor = .white
        web.navigationDelegate = self
        web.scrollView.bounces = false
        webView.addSubview(web)
        web.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        return web
    }()
    
    var resultInfo = ChangeLinkModel()
    var sucNum = 0
    var errNum = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        setTable()
        bindAction()
        requestWeb()
    }
    
    func setUI() {
        title = "转链"
        view.backgroundColor = "#F5F5F5".zm.hex()
        textView.contentInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        resultBtnView.isHidden = true
        succTipView.isHidden = true
        resultView.isHidden = true
    }
    
    func setTable() {
        resultList.register(UINib(nibName: "ChangeLinkResultCell", bundle: nil), forCellReuseIdentifier: "ChangeLinkResultCell")
        resultList.rowHeight = UITableView.automaticDimension
        resultList.estimatedRowHeight = 44
        resultList.delegate = self
        resultList.dataSource = self
        resultList.separatorStyle = .none
        resultList.tableFooterView = UIView()
    }
    
    func setData() {
        sucNum = 0
        errNum = 0
        webBgView.isHidden = true
        nextBtn.isHidden = true
        resultBtnView.isHidden = false
        succTipView.isHidden = false
//        if let jb = resultInfo.jdLink {
////            textView.text = tb.shortUrl
//            sucNum += 1
//        } else {
//            errNum += 1
//        }
        if let tb = resultInfo.tbGoods, let link = resultInfo.tbLink {
            textView.text = link.longTpwd
            sucNum += 1
        } else {
            errNum += 1
        }
        if sucNum == 0 || sucNum == 2 {
            state.text = "转链失败"
            stateImg.image = UIImage(named: "change_link_8")
            copyBtn.isUserInteractionEnabled = false
            copyBtn.backgroundColor = "#CCCCCC".zm.hex()
            resultView.isHidden = true
        } else {
            stateImg.image = UIImage(named: "change_link_7")
            state.text = "转链成功"
            copyBtn.isUserInteractionEnabled = true
            copyBtn.backgroundColor = "#DE3F26".zm.hex()
            resultView.isHidden = false
            resultList.reloadData()
        }
        
        let tipStr = "转链成功\(sucNum)条，失败\(errNum)条"
        let attrString = NSMutableAttributedString(string: tipStr)
        attrString.addAttributes([.foregroundColor: "#DE3F26".zm.hex()], range: NSRange(location: 4, length: "\(sucNum)".count))
        attrString.addAttributes([.foregroundColor: "#DE3F26".zm.hex()], range: NSRange(location: 8+"\(errNum)".count, length: "\(errNum)".count))
        succTip.attributedText = attrString
    }
    
    // MARK: - bindAction
    func bindAction() {
        textView.rx.text.orEmpty.map({$0.count != 0}).subscribe(onNext:{ [unowned self] resp in
            self.nextBtn.isUserInteractionEnabled = resp
            self.tip.isHidden = resp
            self.nextBtn.backgroundColor = resp ? Style.mainColor : Style.disableColor
        }).disposed(by: disposeBag)

        let clearTap = UITapGestureRecognizer()
        clearView.addGestureRecognizer(clearTap)
        clearTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            self.textView.text = ""
            self.stateImg.image = UIImage(named: "change_link_1")
            self.state.text = "待转链"
            self.succTipView.isHidden = true
            self.resultBtnView.isHidden = true
            self.nextBtn.isHidden = false
            self.webBgView.isHidden = false
            self.resultView.isHidden = true
        }).disposed(by: disposeBag)
        
        nextBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.requestLink()
//            let vc = ChangeLinkResultVC()
//            vc.textStr = self.textView.text
//            self.navigationController?.pushViewController(vc, animated: true)
//            vc.clearBlock = { [unowned self] in
//                self.textView.text = ""
//            }
        }).disposed(by: disposeBag)
        
        resetBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.requestLink()
        }).disposed(by: disposeBag)
        
        copyBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            UIPasteboard.general.string = self.textView.text!
            ZMToast.showToast(title: "复制成功")
        }).disposed(by: disposeBag)
        
        wkWeb.scrollView.rx.observeWeakly(CGSize.self, "contentSize").subscribe(onNext: { [unowned self] (change) in
            self.webViewHeight.constant = change!.height
        }).disposed(by: disposeBag)
    }

}

extension ChangeLinkVC: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
            let imgSize = """
            var imgs = document.getElementsByTagName("img")
            for (var i = 0; i < imgs.length; i++) {
                imgs[i].setAttribute('width', '99%')
            }
            """
            webView.evaluateJavaScript(imgSize, completionHandler: nil)
            
            webView.evaluateJavaScript("""
                      var oMeta = document.createElement('meta');
                      oMeta.content = 'width=device-width, initial-scale=1.0, user-scalable=0';
                      oMeta.name = 'viewport';
                      document.getElementsByTagName('head')[0].appendChild(oMeta);
                      """) { flag, error in }
            
        }
        
    }
}

extension ChangeLinkVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sucNum
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ChangeLinkResultCell", for: indexPath) as! ChangeLinkResultCell
        if let tb = resultInfo.tbGoods {
            cell.setUI(tb)
        }
        return cell
    }
}

// MARK: - Request Action
extension ChangeLinkVC {
    func requestWeb() {
        CommonAPI.getDetail(13).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            let json = JSON(resp)
            self.wkWeb.loadHTMLString(json["content"].stringValue.zm.htmlBigSizeString(), baseURL: nil)
        }).disposed(by: disposeBag)
    }
    
    func requestLink() {
        guard let txt = textView.text, txt != "" else {
            return
        }
        if ZMAppShareData.share.userInfo.value?.relationId == "" {
            view.endEditing(true)
            TBAuthTip.show { [unowned self] in
//                if !AlibcTradeUltimateSDK.sharedInstance().loginService().isLogin() {
//                    AlibcTradeUltimateSDK.sharedInstance().loginService().setH5Only(false)
                AlibcTradeUltimateSDK.sharedInstance().tradeService().authorize4AppKey("34031463", appName: "乐购惠生活", appLogo: UIImage.init(named: "icon_512"), currentVC: self) { e, token, exp in
                    if e != nil {
                        ZMToast.showToast(title: "授权失败")
                        return
                    }
                    guard let token = token else {
                        ZMToast.showToast(title: "token 为空")
                        return
                    }
                    ZMToast.showActivity()
                    HomeAPI.tb_userInfo(token).rxRequest(type: String.self).subscribe(onNext:{ [unowned self] resp in
                        if var user = ZMAppShareData.share.userInfo.value {
                            user.relationId = resp
                            ZMAppShareData.share.userInfo.accept(user)
                        }
                        HomeAPI.change_link(txt).rxRequest(type: ChangeLinkModel.self).subscribe(onNext:{ [unowned self] resp in
                            ZMToast.hiddenActivity()
                            self.resultInfo = resp
                            self.setData()
                        }).disposed(by: self.disposeBag)
                    }).disposed(by: self.disposeBag)
                }
                
            }
        } else {
            ZMToast.showActivity()
            HomeAPI.change_link(txt).rxRequest(type: ChangeLinkModel.self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.resultInfo = resp
                self.setData()
            }).disposed(by: disposeBag)
        }
    }
}
